package org.hrhr74.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;


@Component
@Slf4j
public class CacheUtils {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //通用类型的数据存入redis，设置物理时间
    public void set(String key, Object value, Long time, TimeUnit timeUnit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }
    //通用类型的数据存入redis，设置逻辑时间
    public void setWithLogicalExpire(String key, Object value,Long time,TimeUnit timeUnit){
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    //缓存穿透
    public <T,ID>T getPassThrough(String keyPrefix, ID id, Class<T> type,
                                  Function<ID,T> dbFallback,Long time,TimeUnit unit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            T t = JSONUtil.toBean(json, type);
            return t;
        }
        if(json != null){
            return null;
        }
        //查询数据库的操作
        T t = dbFallback.apply(id);
        if(t == null){
            stringRedisTemplate.opsForValue().set(key,"",time,unit);
            return null;
        }
        this.set(key,t,time,unit);
        return t;
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    //缓存击穿——基于逻辑过期
    public <T,ID> T getLogicalExpire(String keyPrefix,String lockKeyPrefix,ID id,Long time,TimeUnit unit
            ,Class<T> type,Function<ID,T> dbFallback){
        String key = keyPrefix + id;
        String lockKey = lockKeyPrefix + id;
        //从redis中查询缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if(StrUtil.isBlank(json)) {
            //不存在
            return null;
        }
        //命中，把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        T t = JSONUtil.toBean((JSONObject) redisData.getData(),type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())) {
            //未过期，返回店铺信息
            return t;
        }
        //已过期，缓存重建
        //1.获取互斥锁
        boolean isLock = tryLock(lockKey);
        //2.判断是否获取成功
        if(isLock) {
            //重建缓存
            try {
                dbFallback.apply(id);
                this.setWithLogicalExpire(key,JSONUtil.toJsonStr(redisData),time,unit);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(lockKey);
            }

        }
        //失败，返回过期的商铺信息
       return t;
    }
    //缓存击穿——基于互斥锁
    public <T,ID> T getWithMutex(String keyPrefix,String lockKeyPrefix,ID id,
                                 Class<T> type,Long time,TimeUnit unit,Function<ID,T> dbFallback) {
        String key = keyPrefix + id;
        String lockKey = lockKeyPrefix + id;

        String json = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            T t = JSONUtil.toBean(json, type);
            return t;
        }
        T t = null;
        try {
            boolean isLock = tryLock(lockKey);
            if(!isLock){
                Thread.sleep(50);
                return getWithMutex(keyPrefix,lockKeyPrefix,id,type,time,unit,dbFallback);
            }
            t = dbFallback.apply(id);
            this.set(key,JSONUtil.toJsonStr(t),time,unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return t;
    }
}
